package esms.action.impl;

import org.apache.log4j.Logger;

import com.thoughtworks.selenium.DefaultSelenium;

import esms.action.ActionFactory;
import esms.action.ActionInterface;
import esms.constants.LocalConstants;

public class LoginXiaonei implements ActionInterface {
	private String url;
	private String userId;
	private String password;
	private static Logger log = Logger.getLogger("LoginXiaonei");

	public static final String USER_NAME_PATH = "//input[@id='email']";
	public static final String USER_PASSWORD_PATH = "//input[@id='password']";
	public static final String SIGN_IN_PATH = "//input[@id='login']";

	public static final String REPLY = "//span[@id=\"gossipReplyCount\"]";
	
	public LoginXiaonei(String url, String userId, String password) {
		this.url = url;
		System.out.println(this.url);
		this.userId = userId;
		this.password = password;
	}

	public void execute(DefaultSelenium selenium) {
		try {
			ActionInterface waitForLoginControl = ActionFactory.getWaitForNodeAction(REPLY,
					LocalConstants.PAUSE_SHORT);

			selenium.open(this.url);
			selenium.type(USER_NAME_PATH, userId);
			selenium.type(USER_PASSWORD_PATH, password);
			selenium.clickAt(SIGN_IN_PATH, "");

			waitForLoginControl.execute(selenium); // wait for user control link

			System.out.println("----------------new reply---------------");
			
			String script = "var my_window = selenium.browserbot.getCurrentWindow();";
			script += "var reply = my_window.document.getElementById('gossipReplyCount');";
			script += "alert(\"value = \" + my_window);";
			script += "alert(\"reply = \" + reply);";
			script += "var tDiv = reply.childNodes[0].textContent;";
			script += "alert(\"tDiv = \" + tDiv);";
			script += "alert(parseInt(tDiv.substring(tDiv.indexOf(\"(\") + 1, tDiv.indexOf(\"(\") + 2)));";
			script += "if(parseInt(tDiv.substring(tDiv.indexOf(\"(\") + 1, tDiv.indexOf(\"(\") + 2)) == 0) {alert(tDiv);}";
			selenium.waitForCondition(script, "1000");
			Thread.sleep(3000);
			System.out.println("----------------new reply---------------");
		} catch (Exception e) {
			log.error(e);
		}
	}
}
